﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	SFJDService
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2017/9/27 14:46:31
//========================================
using SFJDService.SocketHandle;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace SFJDService
{
    public partial class SFJDService : ServiceBase
    {
        static Socket socketMsg;
        static Socket socketUdp;
        static bool serviceRunning;
        public SFJDService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="args">debug:调试模式</param>
        protected override void OnStart(string[] args)
        {
            serviceRunning = true;
            Runtime.Initialize();
            foreach(string str in args)
            {
                if (args[0] == "debug")
                {
                    if(Runtime.win_Debug == null)
                    {
                        Runtime.win_Debug = new Win_Debug();
                        Runtime.win_Debug.Show();
                    }
                    Runtime.isDebugMode = true;
                }
            }
            Runtime.Printf(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "服务已启动！！！");


            new Thread(TcpHandle).Start();
            new Thread(UdpHandle).Start();
            //Launcher.SendUdp2All(typeof(PH01GetData).GetDictianaryKey(), "0");
            new Thread(() =>
            {
                Thread.Sleep(500);
                if (Runtime.thisUser.UserName != null)
                {
                    Launcher.SendUdp2All(typeof(PH07OnLine).GetDictianaryKey(), Runtime.thisUser.UserName + '♠' + Runtime.version.ToString());
                }
                Thread.Sleep(1000);
                if(Runtime.UsersOnLine.activeUsers.Count < 5)
                {
                    List<string> hostsIp = new LanScanning(Runtime.portMsg).GetActiveHosts();
                    foreach(string ip in hostsIp)
                    {
                        Launcher.SendTcp(typeof(PH07OnLine).GetDictianaryKey(), ip, Runtime.thisUser.UserName + '♠' + Runtime.version.ToString());
                    }
                    Thread.Sleep(1000);
                }
                //Launcher.SendUdp2All(typeof(PH01GetData).GetDictianaryKey(), "0");
                new SyncData();
                new Synchronization(SynType.Brigade);
                new Synchronization(SynType.Contact);
                new Synchronization(SynType.User);
            }).Start();
        }

        protected override void OnStop()
        {
            serviceRunning = false;
            Launcher.SendUdp2All(typeof(PH07OffLine).GetDictianaryKey(), Runtime.thisUser.UserName);
            if (socketMsg != null && socketMsg.Connected)
                socketMsg.Close();
            if (socketUdp != null && socketUdp.Connected)
                socketUdp.Close();
            Runtime.Printf(System.Reflection.Assembly.GetExecutingAssembly().GetName() + "服务已正常关闭！！！");
            new Thread(() =>
            {
                Process process = Process.GetCurrentProcess();
                process.Kill();
            }).Start();
        }

        public void Debug()
        {
            //ConsoleManager.Show();
            OnStart(new string[] { "debug"});
        }

        private static void UdpHandle()
        {
            socketUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint edp = new IPEndPoint(IPAddress.Any, Runtime.portUdp);
            socketUdp.Bind(edp);
            EndPoint ep = edp;
            while (serviceRunning)
            {
                try
                {
                    byte[] buff = new byte[Runtime.SocketLenght];
                    int rel = socketUdp.ReceiveFrom(buff, ref ep);
                    new LanHandle(socketUdp, buff);
                }
                catch (Exception e)
                {
                    Runtime.Printf(e.Message);
                }
            }
        }

        private static void TcpHandle()
        {
            socketMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketMsg.Bind(new IPEndPoint(IPAddress.Parse(Runtime.myIP), Runtime.portMsg));
            socketMsg.Listen(0);
            while (serviceRunning)
            {
                Socket cSocket = socketMsg.Accept();
                try
                {
                    byte[] tcpIn = new byte[Runtime.SocketLenght];
                    int recl = cSocket.Receive(tcpIn);
                    new LanHandle(cSocket, tcpIn);
                }
                catch (Exception e)
                {
                    Runtime.Printf(e.Message);
                }
            }
        }

        private static void RecevieMsg(object cSocket)
        {
            Socket oneCSocket = (Socket)cSocket;
            while (serviceRunning)
            {
                try
                {
					byte[] msgIn = new byte[Runtime.SocketLenght];
					int recLength = oneCSocket.Receive(msgIn);
                    string rec = Encoding.ASCII.GetString(msgIn, 0, recLength);
                    Runtime.Printf("客户端Local：" + oneCSocket + " 发来消息：" + rec);
                    //oneCSocket.Close();
                }
                catch (Exception e)
                {
                    Runtime.Printf(e.Message);
                    if (oneCSocket != null && oneCSocket.Connected)
                    {
                        oneCSocket.Shutdown(SocketShutdown.Both);
                        Thread.Sleep(2000);
                        oneCSocket.Close();
                        break;
                    }
                }
            }
        }
    }
}
